﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Upreader.Application;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using System.Threading;
using Upreader.Application.Model;

namespace Upreader.Engine
{
    public class DownloadedSegmentProcessorHandler
    {
        #region Fields

        private readonly DownloadEngineContext _context;

        #endregion // Fields

        #region Constructor

        public DownloadedSegmentProcessorHandler(DownloadEngineContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            _context = context;
        }

        #endregion // Constructor

        #region Methods

        public Task Run(CancellationToken cancellationToken)
        {
            return Task.Factory.StartNew(() =>
            {
                foreach (DownloadSegmentContext segmentContext in _context.DownloadedSegmentContextCollection.GetConsumingEnumerable(cancellationToken))
                {
                    Segment segment = segmentContext.Segment;

                    if (segmentContext.State == DownloadSegmentContextState.Unavailable)
                    {
                        segment.State = SegmentState.Unavailable;
                        _context.Service.UpdateSegment(segment);
                    }
                    else if (segmentContext.State == DownloadSegmentContextState.Caching)
                    {
                        _context.SegmentDataStore.StoreSegment(segmentContext.Segment, segmentContext.DataStream);
                        segmentContext.DataStream = null; // Its cached now
                        segmentContext.State = DownloadSegmentContextState.Cached;

                        // update the segment in the service
                        segment.State = SegmentState.Cached;
                        _context.Service.UpdateSegment(segment);

                        _context.CachedSegmentCollection.Add(segment);
                    }
                    else
                    {
                        throw new InvalidOperationException("Unexpected segment state");
                    }
                }    
            }, cancellationToken, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }

        #endregion // Methods

        #region Helpers

        #endregion // Helpers
    }
}
